package com.leetcode;

import java.util.*;

/**
 * 1. 两数之和
 *
 * @author fy
 * @date 2022/3/31 18:45
 */
public class Solution1 {

    /**
     * 使用hashmap方法求解
     *
     * @param nums
     * @param target
     * @return
     */
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>(nums.length);
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            int other = target - num;
            if (map.containsKey(other)) {
                return new int[]{map.get(other), i};
            }
            map.put(num, i);
        }
        return new int[0];
    }

    public int[] twoSum4(int[] nums, int target) {
        int count = 1, i;
        while (count <= nums.length) {
            i = 0;
            while (i + count < nums.length) {
                if (nums[i] + nums[i + count] == target) {
                    return new int[]{i, i + count};
                }
                i++;
            }
            count++;
        }
        return null;
    }

    public int[] twoSum3(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return null;
    }

    public int[] twoSum1(int[] nums, int target) {
        int[] res = new int[2];
        if (nums == null || nums.length < 2) {
            return res;
        }
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    res[0] = i;
                    res[1] = j;
                    return res;
                }
            }
        }
        return res;
    }

    public int[] twoSum2(int[] nums, int target) {
        int[] res = new int[2];
        if (nums == null || nums.length < 2) {
            return res;
        }
        TreeSet<int[]> newNums = new TreeSet<>(Comparator.comparingInt(a -> a[0]));
        for (int i = 0; i < nums.length; i++) {
            newNums.add(new int[]{nums[i], i});
        }
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            int left = target - num;
            int finalI = i;
            Optional<int[]> other = newNums.stream().filter(item -> item[1] != finalI && item[0] == left).findAny();
            if (other.isPresent()) {
                res[0] = i;
                res[1] = other.get()[1];
                return res;
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{3, 2, 4};
        int target = 6;
        int[] res = new Solution1().twoSum(nums, target);
        System.out.println(res[0] + "|" + res[1]);
    }

}
